import VueFormGenerator from 'vue-form-generator'

let tpl = `
<div class="field-object">
      <div v-if="schema.schema">
        <vue-form-generator :schema="schema.schema" :model="value" :options="formOptions"></vue-form-generator>
      </div>
      <div v-else>
        <table :id="getFieldID(schema)" :class="schema.fieldClasses">
          <tr v-for="(item, index) in value" v-if="index !== 'sstyle'">
            <td>
              {{index}} {{keyTypes[index]}}
            </td>
              <template v-if="index === 'style'">
              <td>
                      <styleinput :value="value[index]"
                             @input="onStyleInput($event, index)"
                             ></styleinput>
              </td>
              </template>
               <template v-else-if="index === 'class'">
                <td>
                        <proparrinput :value="value[index]"
                               @input="onClassInput($event, index)"
                               ></proparrinput>
                </td>
              </template>
              <template v-else>
                          <td v-if="keyTypes[index] === 'string' && !isLikeArray(value[index])">
                <el-input  size="small" v-model="value[index]" 
                @change="onInput"></el-input>
              </td>
              <td v-if="keyTypes[index] === 'boolean'">
                <el-checkbox size="small" v-model="value[index]"  @change="onInput"></el-checkbox>
              </td>
              <td v-if="keyTypes[index] === 'array' || isLikeArray(value[index]) ">  
                   <proparrinput :value="value[index]"
                             @input="onPropInput($event, index)"
                             ></proparrinput>
              </td>
              <td v-if="keyTypes[index] === 'number'">
                <el-input   size="small" v-model.number="value[index]"  @change="onInput"></el-input>
              </td>
</template>
            <td>
              <el-button size="small" type="danger" 
              @click="removeElement(index)">x</el-button>
            </td>
          </tr>
        </table>
<!--        <div>{{isComponent}}</div>-->
        <div hidden>
          <component :is="isComponent" ref="com"></component>
        </div>
        <template v-if="neededit">
          <div style="display: flex">
              <el-select v-model="newKeyType" size="small" style="width: 120px;">
      <el-option value="string">String</el-option>
      <el-option value="array">Array</el-option>
      <el-option value="boolean">Boolean</el-option>
    </el-select>
    <come-prop @change="addKey"></come-prop>
</div>
          
</template>
      </div>
    </div>
`

let abstractFieldMixin = VueFormGenerator.abstractField
VueFormGenerator.abstractField.computed.value = {
  cache: false,
  get: function () {
    let val
    // if (isFunction(objGet(this.schema, "get"))) {
    //   val = this.schema.get(this.model);
    // } else {
    //   val = objGet(this.model, this.schema.model);
    // }

    val = this.model
    return this.formatValueToField(val)
  },
  // setter
  set: function (newValue) {
    let oldValue = this.value
    newValue = this.formatValueToModel(newValue)

    // if (isFunction(newValue)) {
    //   newValue(newValue, oldValue);
    // } else {
    //   this.updateModelValue(newValue, oldValue);
    // }
    this.updateModelValue(newValue, oldValue)
  },
}

var validatePass = (rule, value, callback) => {
  let validateSelRegexp = /^[:a-zA-Z]{1}[\w-:]*$/g
  if (value === '') {
    callback(new Error('请输入key'))
  } else {
    let isPassed = validateSelRegexp.test(value)
    // console.log('isPassed', isPassed, value)
    if (!isPassed) {
      callback(new Error('首字母为字母'))
    } else {
      callback()
    }
  }
}

import kebabCase from 'lodash/kebabCase'

let searchMixin = {
  data() {
    return {
      restaurants: [],
    }
  },
  methods: {
    querySearch(queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString ?
        restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    loadAll(arr) {
      return arr.map(v => {
        return {
          value: kebabCase(v),
        }
      })
    },
    handleSelect(item) {
      // console.log(item);
    },
  },
  mounted() {
  },
}

import proparrinput from '../pageapp/proparrinput'
import styleinput from '../pageapp/styleinput'

export let FieldObject = {
  template: tpl,
  props: ['comname', 'neededit'],
  components: {
    proparrinput: proparrinput(),
    styleinput: styleinput(),
  },
  mixins: [
    abstractFieldMixin,
    searchMixin,
  ],
  created() {
    if (!this.value) {
      this.value = {}
    }
  },
  mounted() {
    // console.log(this.comname, this.$refs.com)
    this.isComponent = this.comname
    this.$nextTick(async () => {
      if (this.$refs.com && this.$refs.com.$options) {
        this.restaurants = this.loadAll(this.$refs.com.$options._propKeys)
      } else {
        if (window.vvg.getSuggestions) {
          let _a = await window.vvg.getSuggestions(this.isComponent)
          this.restaurants = this.loadAll(_a)
        } else {
          this.restaurants = []
        }
      }
    })
    if (!this.value) return
    let valueKeys = Object.keys(this.value)
    let keyTypes = {}
    for (let i = 0; i < valueKeys.length; i++) {
      let key = valueKeys[i]
      keyTypes[key] = typeof this.value[key]
    }
    this.keyTypes = keyTypes
  },
  data() {
    return {
      newKeyType: 'string',
      newKeyName: '',
      keyTypes: {},
      rules: {
        name: [
          {validator: validatePass, trigger: 'change'},
        ],
      },
      isComponent: '',
    }
  },
  methods: {
    onInput() {
      this.fireCom()
    },
    removeElement(index, item) {
      let value = this.value
      this.$emit('delete', JSON.parse(JSON.stringify(index)))
      delete value[index]
      this.value = {...value}
      let keyTypes = this.keyTypes
      delete keyTypes[index]
      this.keyTypes = {...keyTypes}
    },
    addKey(propName) {
      this.$set(this.value, propName, undefined)
      this.$set(this.keyTypes, propName, this.newKeyType)
      this.$nextTick(() => {

      })
    },
    onPropInput(e, index) {
      this.value[index] = Object.values(e).join()
      // console.log(e, this.value[index])
      this.fireCom()
    },
    onClassInput(e, index) {
      this.value[index] = Object.values(e).join(' ')
      this.fireCom()
    },
    onStyleInput(e, index) {
      let keys = Object.keys(e)
      let arr = []
      keys.forEach(key => {
        arr.push(`${key}: ${e[key]}`)
      })
      this.value[index] = arr.join(';')
      console.log(e)
      this.fireCom()
    },
    fireCom() {
      this.$emit('propinput', this.value)
    },
    isLikeArray(v) {
      // console.log('isLikeArray', v)
      if (typeof v !== 'string') {
        return false
      }
      if (!v) {
        return false
      }
      return v.indexOf(',') > -1
    }
  },
}
